// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/exception/exceptions.h>
#include <melon/likely.h>
#include <array>
#include <cstdio>
#include <string>

namespace kumo {
    namespace pollux {
        namespace dwio {
            namespace common {
                void verify_range(uint64_t v, uint64_t rangeMask) {
                    auto mv = (v & rangeMask);
                    if (UNLIKELY(mv != 0 && mv != rangeMask)) {
                        corrupt("Integer data out of range");
                    }
                }

                void verify(bool c, std::string fmt...) {
                    if (UNLIKELY(!c)) {
                        va_list ap;
                        va_start(ap, fmt);
                        auto s = error_string(fmt, ap);
                        va_end(ap);
                        throw ParseError(s);
                    }
                }

                [[noreturn]] void corrupt(std::string fmt...) {
                    va_list ap;
                    va_start(ap, fmt);
                    auto s = error_string(fmt, ap);
                    va_end(ap);
                    throw ParseError(s);
                }

                std::string error_string(std::string fmt, va_list ap) {
                    std::array<char, 1024> buf;
                    vsnprintf(buf.data(), buf.size(), fmt.data(), ap);
                    buf[buf.size() - 1] = 0;
                    return std::string(buf.data());
                }

                std::string format_error_string(std::string fmt...) {
                    va_list ap;
                    va_start(ap, fmt);
                    auto s = error_string(fmt, ap);
                    va_end(ap);
                    return s;
                }
            } // namespace common
        } // namespace dwio
    } // namespace pollux
} // namespace kumo
